if not qxnetlib then
	qxnetlib = {};
	require("cocos.framework.components.event"):bind(qxnetlib);    
	qxnetlib.CLIENT_PK_SIGN  = 0x55AA
	qxnetlib._host = "127.0.0.1";
	qxnetlib._port = 7000;
	qxnetlib._tcp = nil;
	qxnetlib.needTryConnectTime = 5
	qxnetlib._failReConnectTime = 5;	
	qxnetlib.sendfailTime = 0
	qxnetlib.reConnectTime = 1;	--设置重连的计划时间，如果为0则不需要重连，单位为s, ms = s / 1000
	qxnetlib._recvScheduler = nil;	--接收数据的桢事件
	qxnetlib._reConnectScheduler = nil;	--重连事件
	qxnetlib.EVENT_SERVER_CONNECTED = "EVENT_SERVER_CONNECTED";	--连接成功的事件
	qxnetlib.EVENT_SERVER_RECONNECTED = "EVENT_SERVER_RECONNECTED";	--连接成功的事件
	qxnetlib.EVENT_SERVER_CONNECT_FAIL = "EVENT_SERVER_CONNECT_FAIL";	--连接失败的事件
	qxnetlib.EVENT_TRY_RECONNECTED = "EVENT_TRY_RECONNECTED";	--重新连接失败的事件

	qxnetlib.EVENT_TRY_C_RECONNECTED = "EVENT_TRY_C_RECONNECTED";	--重新连接失败的事件

	qxnetlib.EVENT_SOCKET_CLOSED = "EVENT_SOCKET_CLOSED";	--连接断开的事件
	qxnetlib.EVENT_SOCKET_REVC_DATA = "EVENT_SOCKET_REVC_DATA";	--接收到数据的事件
	qxnetlib._recvDataCash = {};	--缓存数据块
	qxnetlib._encodeKey = "*(H#@@HJgnj&^fjdk556dede48^@g";	--加密秘钥
	qxnetlib.socket_state_init = -1		--// 初始状态
	qxnetlib.socket_state_connect_ing= 0	--// 正在连接
	qxnetlib.socket_state_connect_sucess = 1--// 连接成功状态
	qxnetlib.socket_state_connect_failed = 2--// 连接失败状态
	qxnetlib.socket_state_connect_close = 3 --// 连接关闭状态
end
local scheduler = cc.Director:getInstance():getScheduler()
local protocol = require("gamemodel.protocol")
require("socket.core")
local socket = require("socket");
local qxpacket = require("net.qxpacket");
local QueryExit = appdf.req(appdf.CLIENT_SRC.."app.views.layer.other.QueryDialog")
local nRand = 661

qxnetlib.connectServer = function(host, port)
	if host then qxnetlib._host = host; end
	if port then qxnetlib._port = port; end
	qxnetlib._failReConnectTime = qxnetlib.needTryConnectTime
	print("connectServer",host, port)
	if not qxnetlib._tcp then
		qxnetlib._tcp = mycs.ClientSocket:create()
	end
	qxnetlib._tcp:connect_server(qxnetlib._host, qxnetlib._port);
	qxnetlib.netStatus = qxnetlib.socket_state_connect_ing
	qxnetlib:dispatchEvent({name = qxnetlib.EVENT_SERVER_CONNECTED});
	qxnetlib._setRecvCallBackInFrame()
	-- qxnetlib._reConnectServer()
end

qxnetlib._doConnect = function()
	local status = qxnetlib._tcp:get_state();
	print("_doConnect>>>>>", status)
	qxnetlib.netStatus = status
	local isconnected = status ~= qxnetlib.socket_state_connect_failed 
	qxnetlib.disconect  = not isconnected
	return isconnected and status or false
end

local max_proc_count = 0;
local cur_proc_count = 0;

--桢函数
qxnetlib._onRecvBuffCallBack = function(recvCount)
	recvCount = recvCount or 0
	local msgCount,wCtrl,wMsgID,recvstr = qxnetlib._tcp:recv_data()
	if msgCount > 0  then
		qxnetlib.netStatus = qxnetlib.socket_state_connect_sucess
		local recvjs
		if(wMsgID == protocol.SM_GAME_STRUCT_MESSAGE) then
			local buffrec = qxpacket.new();
			buffrec:setPack(recvstr)
			local len = buffrec:readUnShort()
			local subid = buffrec:readInt()
			recvjs = {}
			recvjs.subid = subid
			recvjs.buff = buffrec
		else			
			if recvstr ~= ""   then
				print(recvstr)
				recvjs = cjson.decode(recvstr)
				wMsgID = recvjs.msgid or wMsgID
			end
			dump(recvjs,"recvjs>>>>>")
		end
	
		qxnetlib.onRecvBuff(wCtrl,wMsgID,recvjs);
		msgCount = msgCount - 1 
		recvCount = recvCount + 1
		-- 游戏消息一次读取   大厅消息 一帧一条
		local isGameMsg =  yl.CUR_SCENE_TAG == yl.SCENE_GAME or  yl.CUR_SCENE_TAG == yl.SCENE_ROOM or  yl.CUR_SCENE_TAG == yl.SCENE_ROOMLIST or 
		protocol.SM_GAME_STRUCT_MESSAGE == wMsgID or protocol.SM_GAME_MESSAGE == wMsgID 

		if isGameMsg and  msgCount > 0 and recvCount < 10  then
			if device.platform ~= "windows" and  appdf.isTest == nil then
				xpcall(function( ... )
					qxnetlib._onRecvBuffCallBack(recvCount) 
				end,function( ... )
					print("_onRecvBuffCallBack>>>>> error",wMsgID)
				end)
			else
				qxnetlib._onRecvBuffCallBack(recvCount) 
			end
			
			-- qxnetlib._onRecvMaxBuffCallBack(msgCount) 
		end
	end
end

qxnetlib._setRecvCallBackInFrame = function()
	--连接成功了，需要设置一个检查接收数据包的桢函数
	-- qxnetlib:dispatchEvent({name = qxnetlib.EVENT_SERVER_CONNECTED});	--抛出连接成功的事件
	if qxnetlib._recvScheduler then	--清除旧值
		scheduler:unscheduleScriptEntry(qxnetlib._recvScheduler);
		qxnetlib._recvScheduler = nil;
	end
	qxnetlib.tickcount = 1
	qxnetlib._recvScheduler = scheduler:scheduleScriptFunc( qxnetlib._onRecvBuffCallBack , 0.1,false);
end

qxnetlib._resumeRecv = function() 
	if not qxnetlib._recvScheduler  then
		qxnetlib._recvScheduler = scheduler:scheduleScriptFunc(qxnetlib._onRecvBuffCallBack, 0.1,false);
	end
end

--暂停
qxnetlib._pauseRecv = function()
	if qxnetlib._recvScheduler then
		scheduler:unscheduleScriptEntry(qxnetlib._recvScheduler);
		qxnetlib._recvScheduler = nil;
		-- qxnetlib:removeAllEventListenersForEvent(qxnetlib.EVENT_SERVER_CONNECTED);
	end
end

qxnetlib._onClose = function()
	-- print(debug.traceback( "_onClose",2))
	-- qxnetlib._recvDataCash = {}
	if qxnetlib.netStatus == qxnetlib.socket_state_connect_sucess then
		qxnetlib.netStatus = qxnetlib.socket_state_connect_close
		
	end
	qxnetlib.onCloseSocket()

end

qxnetlib.onCloseSocket = function()
	print(debug.traceback( "onCloseSocket",2))
	qxnetlib._tcp:close_socket();
end

if not qxnetlib.cmdlib then
    qxnetlib.cmdlib = {};
end

if not qxnetlib.cmdHandler then
    qxnetlib.cmdHandler = {};
end

qxnetlib.regCmd = function(cmd, callback)
	assert(cmd);
	assert(callback);
	--assert(not cmdlib.cmdHandler[cmd], tostring(cmd) .. "exists");
    qxnetlib.cmdHandler[cmd] = function(buff)
        callback(buff);
    end
end


qxnetlib.send = function(wCtrl,wMsgID,bodyStr,bForceSend)
	if qxnetlib.netStatus ~= qxnetlib.socket_state_connect_sucess then
		print("网络异常 发送失败>>>>>>>>>>>>>>>")
		return
	end
	bodyStr = bodyStr or ""
	print("send_data>>>>",wCtrl,wMsgID,bodyStr,#bodyStr)
	local rec = qxnetlib._tcp:send_data(wCtrl,wMsgID,bodyStr,#bodyStr)
	if rec ~= 0 then
		local runScene = cc.Director:getInstance():getRunningScene()
		if nil ~= runScene then
			-- showToastNoFade(runScene, "发送数据失败", 1)
		end
		return false
	end
	return true
end

-- STRUCT
qxnetlib.sendStruct = function(wMsgID, buffpacket, bForceSend)
	local len = buffpacket:getLen()
	local headpacket = qxpacket.new()
	headpacket:writeUnShort(len)
	headpacket:writeInt(wMsgID)
	local bodyStr = headpacket:getPack()
	if(len > 0) then
		bodyStr = bodyStr..buffpacket:getPack()
	end
	qxnetlib.send(protocol.CTRL_CLIENT_CLUSTER,207,bodyStr,bForceSend)
end

function qxnetlib.checkParams( ... )
    nRand = nRand  + 1
	if nRand > 9999 then
		 nRand = 661
	end
end

function qxnetlib.isDisConnect( ... )
	return  qxnetlib.disconect
end

function qxnetlib._reConnectServer( ... )
	-- body
	qxnetlib:dispatchEvent({name = qxnetlib.EVENT_TRY_C_RECONNECTED});
end

return qxnetlib

